package paket;

import Engine.Engine;
import Engine.EngineNg;
import admin.gameInterface;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;



// http://www.java-forums.org/new-java/8091-how-can-i-draw-board-2d-array.html

public class BoardPanel extends JPanel {
    public BoardPanel board;
    SquareRx[][] squares;
    Hero [][] heroes;
    Thread lisTR;
    private  int PAD = 20;
    public static int ROWS = 9;
    public static int COLS = 9;
    public static int ourTeam = 0;
    public static int rakipTeam = 0;
    private NewJApplet1 aplet;
    //private Graphics board_g =null;
    // kaydırma baslangic
    public int rowSelected=-1;
    public int colSelected=-1;

    public int selectedPoint_X=-1;
    public int selectedPoint_Y=-1;

    public int movePoint_X=-1;
    public int movePoint_Y=-1;
    Image[] img;
    Thread tr;
    int w;  // board genişliği
    int h;  // board yüksekliği
    int x, y;

    public gameInterface preGame;
    public  gameInterface postGame;
    NetworkConnection connect;
    Image image;
    Hero tempHero = null;
    MediaTracker mt;
    BufferedImage bi;


//kaydırma bitis

    public NewJApplet1 getAplet() {
        return aplet;
    }

    public void setAplet(NewJApplet1 aplet) {
        this.aplet = aplet;
    }


   // public Graphics getBoard_g() {
    //}
/*
    public void setCOLS(int COLS) {
        this.COLS = COLS;
    }

    public void setROWS(int ROWS) {
        this.ROWS = ROWS;
    }

    public int getCOLS() {
        return COLS;
    }

    public int getPAD() {
        return PAD;
    }

    public int getROWS() {
        return ROWS;
    }
*/
    public BoardPanel(){
        super();
        init();
        addMouseListener(ml);

    }
  
    private void init() {
        lisTR = new listenThread(this);
        bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
        lisTR.start();
        try {
            image = getToolkit().getImage("images/empty.gif");
        } catch (Exception e) {
            System.out.println("resim bulamadımm...");
        }
        mt = new MediaTracker(this);
        mt.addImage(image, 0);// buradaki 0 baslangicta hangi resim görüneceğini belirtir.
        try {
            mt.waitForAll();
        } catch (Exception e) {
            System.out.println("Exception while loading image.");
        }

        if (image.getWidth(this) == -1) {
            System.out.println("no gif file");
            System.exit(0);
        }
        

        Graphics2D big = bi.createGraphics();

        big.drawImage(image, 0, 0, this);
        connect = new NetworkConnection();
        board = this;
        
        heroes = new Hero[ROWS][COLS];
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

       
        
       // g2.drawImage(bi, x, y, board);
        
        if(squares == null) {
            initSquares();
        }
        // Draw squares.
        g2.setPaint(Color.blue);
       
        g2.draw3DRect(x, y, WIDTH, WIDTH, true);
        for(int i = 0; i < ROWS; i++) {
            for(int j = 0; j < COLS; j++) {
                squares[i][j].draw(g2, (((double)(board.getSize().getWidth() - 2*PAD)/COLS)*i)+PAD , (((double)(board.getSize().height - 2*PAD)/ROWS)*j)+PAD );
                //g2.drawString("("+i+","+j+")",(int)(((board.getSize().getWidth() - 2*PAD)/COLS)*i)+PAD , (int)(((board.getSize().height - 2*PAD)/ROWS)*j)+PAD +10);
                if (heroes[i][j] != null){
                    heroes[i][j].draw(g,j,i,PAD, (double)(board.getSize().getWidth() - 2*PAD)/COLS, (double)(board.getSize().height - 2*PAD)/ROWS ,board);
                }
                g2.drawImage(bi, x, y, board);
            }
        }
        for(int i = 0; i < ROWS; i++) {
            for(int j = 0; j < COLS; j++) {
                g2.drawString("("+j+","+i+")",(int)(((board.getSize().getWidth() - 2*PAD)/COLS)*i)+PAD , (int)(((board.getSize().height - 2*PAD)/ROWS)*j)+PAD +10);
            }
        }
        //g2.drawImage(bi, x, y, board);
    }

    public void initSquares() {
        squares = new SquareRx[ROWS][COLS];
        w = this.getWidth();
        h = this.getHeight();
        double xInc = (double)(w - 2*PAD)/COLS;
        double yInc = (double)(h - 2*PAD)/ROWS;
        for(int i = 0; i < ROWS; i++) {
            double y = PAD + i*yInc;
            for(int j = 0; j < COLS; j++) {
                double x = PAD + j*xInc;
                Rectangle2D.Double r =
                    new Rectangle2D.Double(x, y, xInc, yInc);
                squares[i][j] = new SquareRx(i, j, r);

                if ( (i+j)%2 == 1){
                  squares[i][j].bgColor= Color.WHITE;
                }
            }
        }
    }
    
    public void oynat(int i, int j, String res){
        //imageleri önceden yuklemek gerek image ' e
        ImageSelect(res);
        imageLoad();
        imageDraw();
       
         x=i;
         y=j;
        // repaint();
    }
    public void ImageSelect(String str){
           image = getToolkit().getImage(str);
          // System.out.println(str);
           mt.addImage(image, 1);
    }
    public void imageLoad(){
            bi = new BufferedImage(100, 100,
            BufferedImage.TYPE_INT_ARGB);
    }
    public void imageDraw(){
            Graphics2D big = bi.createGraphics();
            big.drawImage(image, 0, 0, board); //gif'in oynayabilmesi için gerekli yoksa jpg gibi kalır
    }
    public void tabloYaz(){
        JTable tablo= aplet.getjTable1();
        tablo.setValueAt(postGame.ba1_p, 0, 1);
        tablo.setValueAt(postGame.ba2_p, 1, 1);
        tablo.setValueAt(postGame.bm1_p, 2, 1);
        tablo.setValueAt(postGame.bm2_p, 3, 1);
        tablo.setValueAt(postGame.bo1_p, 4, 1);
        tablo.setValueAt(postGame.bo2_p, 5, 1);
        tablo.setValueAt(postGame.bk1_p, 6, 1);
        tablo.setValueAt(postGame.bk2_p, 7, 1);

        tablo.setValueAt(postGame.ra1_p, 0, 3);
        tablo.setValueAt(postGame.ra2_p, 1, 3);
        tablo.setValueAt(postGame.rm1_p, 2, 3);
        tablo.setValueAt(postGame.rm2_p, 3, 3);
        tablo.setValueAt(postGame.ro1_p, 4, 3);
        tablo.setValueAt(postGame.ro2_p, 5, 3);
        tablo.setValueAt(postGame.rk1_p, 6, 3);
        tablo.setValueAt(postGame.rk2_p, 7, 3);
    }
    public void move(){
        tr=new HareketThread(this);
        tr.start();
    }
    public void gameDraw(){
        //we are the blueee
        for(int i = 0; i < ROWS; i++) {

            for(int j = 0; j < COLS; j++) {
              heroes[i][j] = null;
            }
        }
        ourTeam = postGame.team;
        rakipTeam = 1 - ourTeam;
        System.out.println(postGame.team);
        heroes = Hero.makeHero(postGame);
        gameInterface sendGame = new gameInterface();
        sendGame = Hero.makeGamePad(heroes, sendGame);
        System.out.println(postGame.team+":"+sendGame.team);
        System.out.println(postGame.status+":"+sendGame.status);
        System.out.println(postGame.equals(sendGame));

       

    }
    private MouseListener ml = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(!isInGrid(p)) return;

            double xInc = (double)(board.getSize().getWidth() - 2*PAD)/COLS;
            double yInc = (double)(board.getSize().height - 2*PAD)/ROWS;
            int row = (int)((p.y-PAD)/yInc);
            int col = (int)((p.x-PAD)/xInc);
            System.out.println("Board click:" +row +":"+col);
            boolean isSelected = squares[row][col].isSelected();
            squares[row][col].setSelected(!isSelected);

            EngineNg en=new EngineNg();
      
                    //lis=en.biz(heroes,-1);

            postGame=en.play(postGame, ourTeam);
                    //Hero.makeGamePad(heroes, postGame);
                    tabloYaz();

                    heroes=Hero.makeHero(postGame);
                
               
            ArrayList<paket.Hero[][]> lis=new ArrayList<paket.Hero[][]>();
            System.out.println("Tahta hamlesiii");
                Hero.makeGamePad(heroes,postGame);
                postGame.team = 1 - postGame.team;
                connect.WriteGame(postGame);
                System.out.println("Takim nedir ki?: "+postGame.team);
                aplet.getjLabel1().setText("Sıra digerindeeee");
        }

    };

    public boolean isInGrid(Point p) {
        Rectangle r = getBounds();
        r.grow(-PAD, -PAD);
        return r.contains(p);
    }
    public static void main(String[] args) {
        BoardPanel test = new BoardPanel();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(test);
        f.setSize(400,400);
        f.setLocation(100,100);
        f.setVisible(true);
        test.addComponentListener(test.cl);
    }

    private ComponentListener cl = new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            squares = null;
            repaint();
        }
    };
}
